﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Security.Permissions;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Dos.Common
{
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [DefaultProperty("Height")]
    [Designer(typeof(CaptchaControlDesigner))]
    [ParseChildren(true, "Fonts")]
    [PersistChildren(false)]
    [ToolboxData("<{0}:Captcha runat=\"server\"></{0}:Captcha>")]
    public class CaptchaControl : WebControl
    {
        internal static string sessionName;

        internal static bool allowCharRotation;

        internal static bool allowDistortion;

        internal static Color backgroundColor;

        internal static int captChaLength;

        internal static FontMode codeFontMode;

        internal static List<CaptchaFontArrayItem> fonts;

        internal static FontSizeMode codeFontSizeMode;

        internal static ColorMode codeStringFillingMode;

        internal static CharacterContentField contentField;

        internal static int expireTime;

        internal static Color foregroundColor;

        internal static int imageHeight;

        internal static int imageWidth;

        internal static bool isBackgroundDynamic;

        internal static bool isCaseSensitive;

        internal static bool isForegroundDynamic;

        private bool livePreview;

        internal static NoisyRate noiseMode;

        internal static int stringOpacity;

        internal static string tooltip;

        /// <summary>
        /// 设置是否对验证码图片中的字符进行旋转形变
        /// </summary>
        [Category("Appearance")]
        [Description("设置是否对验证码图片中的字符进行旋转形变。")]
        public bool AllowCharRotation
        {
            get
            {
                return CaptchaControl.allowCharRotation;
            }
            set
            {
                CaptchaControl.allowCharRotation = value;
            }
        }

        /// <summary>
        /// 设置是否对验证码图片中的字符进行扭曲形变
        /// </summary>
        [Category("Appearance")]
        [Description("设置是否对验证码图片中的字符进行扭曲形变。")]
        public bool AllowDistortion
        {
            get
            {
                return CaptchaControl.allowDistortion;
            }
            set
            {
                CaptchaControl.allowDistortion = value;
            }
        }

        /// <summary>
        /// 验证码背景颜色
        /// </summary>
        [Description("验证码背景颜色。")]
        public override Color BackColor
        {
            get
            {
                return CaptchaControl.backgroundColor;
            }
            set
            {
                CaptchaControl.backgroundColor = value;
            }
        }

        /// <summary>
        /// 验证码包含的字符数（1～10位）。
        /// </summary>
        [Category("Appearance")]
        [Description("验证码包含的字符数（1～10位）。")]
        public int CaptchaLength
        {
            get
            {
                return CaptchaControl.captChaLength;
            }
            set
            {
                CaptchaControl.captChaLength = (value < 1 ? 1 : value);
                CaptchaControl.captChaLength = (CaptchaControl.captChaLength > 10 ? 10 : CaptchaControl.captChaLength);
            }
        }

        /// <summary>
        /// 验证码前景（字符）填充不透明度（0%～100%）
        /// </summary>
        [Category("Appearance")]
        [Description("验证码前景（字符）填充不透明度（0%～100%）。")]
        public int CodeOpacity
        {
            get
            {
                return CaptchaControl.stringOpacity;
            }
            set
            {
                CaptchaControl.stringOpacity = (value < 0 ? 0 : value);
                CaptchaControl.stringOpacity = (CaptchaControl.stringOpacity > 100 ? 100 : CaptchaControl.stringOpacity);
            }
        }

        /// <summary>
        /// 验证码前景（字符）色彩填充模式
        /// </summary>
        [Category("Appearance")]
        [Description("验证码前景（字符）色彩填充模式。")]
        public ColorMode ColorMode
        {
            get
            {
                return CaptchaControl.codeStringFillingMode;
            }
            set
            {
                CaptchaControl.codeStringFillingMode = value;
            }
        }

        /// <summary>
        /// 验证码字符集组成
        /// </summary>
        [Category("Appearance")]
        [Description("验证码字符集组成。")]
        public CharacterContentField ContentField
        {
            get
            {
                return CaptchaControl.contentField;
            }
            set
            {
                CaptchaControl.contentField = value;
            }
        }

        /// <summary>
        /// 验证码的有效期（10～300秒；置零则永不过期）
        /// </summary>
        [Category("Action")]
        [Description("验证码的有效期（10～300秒；置零则永不过期）。")]
        public int ExpireTime
        {
            get
            {
                return CaptchaControl.expireTime;
            }
            set
            {
                CaptchaControl.expireTime = (value == 0 || value >= 10 ? value : 10);
                CaptchaControl.expireTime = (CaptchaControl.expireTime > 300 ? 300 : CaptchaControl.expireTime);
            }
        }

        /// <summary>
        /// 字体
        /// </summary>
        [Browsable(false)]
        public override FontInfo Font
        {
            get
            {
                return base.Font;
            }
        }

        /// <summary>
        /// 验证码字符字体变化模式
        /// </summary>
        [Category("Appearance")]
        [Description("验证码字符字体变化模式。")]
        public FontMode FontMode
        {
            get
            {
                return CaptchaControl.codeFontMode;
            }
            set
            {
                CaptchaControl.codeFontMode = value;
            }
        }

        /// <summary>
        /// 验证码字符字体集（仅在FontMode为“FontLimited”时有效）
        /// </summary>
        [Category("Appearance")]
        [Description("验证码字符字体集（仅在FontMode为“FontLimited”时有效）。")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        public List<CaptchaFontArrayItem> Fonts
        {
            get
            {
                if (CaptchaControl.fonts == null)
                {
                    CaptchaControl.fonts = new List<CaptchaFontArrayItem>();
                }
                return CaptchaControl.fonts;
            }
            set
            {
                CaptchaControl.fonts = value;
            }
        }

        /// <summary>
        /// 验证码字符尺寸变化模式
        /// </summary>
        [Category("Appearance")]
        [Description("验证码字符尺寸变化模式。")]
        public FontSizeMode FontSizeMode
        {
            get
            {
                return CaptchaControl.codeFontSizeMode;
            }
            set
            {
                CaptchaControl.codeFontSizeMode = value;
            }
        }

        /// <summary>
        /// 验证码前景（字符）颜色（仅在ForeColorFillingMode为“PureColor”时有效）
        /// </summary>
        [Description("验证码前景（字符）颜色（仅在ForeColorFillingMode为“PureColor”时有效）。")]
        public override Color ForeColor
        {
            get
            {
                return CaptchaControl.foregroundColor;
            }
            set
            {
                CaptchaControl.foregroundColor = value;
            }
        }

        /// <summary>
        /// 验证码控件高度
        /// </summary>
        [Description("验证码控件高度。")]
        public override Unit Height
        {
            get
            {
                base.Height = Unit.Pixel(CaptchaControl.imageHeight);
                return base.Height;
            }
            set
            {
                base.Height = (Convert.ToInt32(value.Value) <= 0 ? Unit.Pixel(0) : value);
                CaptchaControl.imageHeight = Convert.ToInt32(base.Height.Value);
            }
        }

        /// <summary>
        /// 验证码背景动态模式设定
        /// </summary>
        [Category("Appearance")]
        [Description("验证码背景动态模式设定。")]
        public bool IsBackgroundDynamic
        {
            get
            {
                return CaptchaControl.isBackgroundDynamic;
            }
            set
            {
                CaptchaControl.isBackgroundDynamic = value;
            }
        }

        /// <summary>
        /// 设置校验验证码时是否区分大小写（仅对英文字母有效）
        /// </summary>
        [Category("Action")]
        [Description("设置校验验证码时是否区分大小写（仅对英文字母有效）。")]
        public bool IsCaseSensitive
        {
            get
            {
                return CaptchaControl.isCaseSensitive;
            }
            set
            {
                CaptchaControl.isCaseSensitive = value;
            }
        }

        /// <summary>
        /// 验证码前景动态模式设定
        /// </summary>
        [Category("Appearance")]
        [Description("验证码前景动态模式设定。")]
        public bool IsForegroundDynamic
        {
            get
            {
                return CaptchaControl.isForegroundDynamic;
            }
            set
            {
                CaptchaControl.isForegroundDynamic = value;
            }
        }

        /// <summary>
        /// 开启或关闭验证码图片设计时预览
        /// </summary>
        [Description("开启或关闭验证码图片设计时预览。")]
        public LivePreviewMode LivePreview
        {
            get
            {
                return (!this.livePreview ? LivePreviewMode.Off : LivePreviewMode.On);
            }
            set
            {
                if (value != LivePreviewMode.On)
                {
                    this.livePreview = false;
                }
                else
                {
                    this.livePreview = true;
                }
            }
        }

        /// <summary>
        /// 设置验证码图片的噪化程度
        /// </summary>
        [Category("Appearance")]
        [Description("设置验证码图片的噪化程度。")]
        public NoisyRate NoiseMode
        {
            get
            {
                return CaptchaControl.noiseMode;
            }
            set
            {
                CaptchaControl.noiseMode = value;
            }
        }

        /// <summary>
        /// 验证码Session名称
        /// </summary>
        [Description("验证码Session名称。")]
        public string SessionName
        {
            get
            {
                return CaptchaControl.sessionName;
            }
            set
            {
                CaptchaControl.sessionName = value;
            }
        }

        /// <summary>
        /// 鼠标移过验证码图片时的提示
        /// </summary>
        [Description("鼠标移过验证码图片时的提示。")]
        public override string ToolTip
        {
            get
            {
                return CaptchaControl.tooltip;
            }
            set
            {
                CaptchaControl.tooltip = value;
            }
        }

        /// <summary>
        /// 验证码控件宽度
        /// </summary>
        [Description("验证码控件宽度。")]
        public override Unit Width
        {
            get
            {
                base.Width = Unit.Pixel(CaptchaControl.imageWidth);
                return base.Width;
            }
            set
            {
                base.Width = (Convert.ToInt32(value.Value) <= 0 ? Unit.Pixel(0) : value);
                CaptchaControl.imageWidth = Convert.ToInt32(base.Width.Value);
            }
        }

        static CaptchaControl()
        {
            CaptchaControl.sessionName = "Dos.Captcha";
            CaptchaControl.allowCharRotation = true;
            CaptchaControl.allowDistortion = true;
            CaptchaControl.backgroundColor = Color.White;
            CaptchaControl.captChaLength = 4;
            CaptchaControl.codeFontMode = FontMode.FontLimited;
            CaptchaControl.codeFontSizeMode = FontSizeMode.SizeVary;
            CaptchaControl.codeStringFillingMode = ColorMode.RandomColor;
            CaptchaControl.contentField = CharacterContentField.DigitAndLetter;
            CaptchaControl.expireTime = 60;
            CaptchaControl.foregroundColor = Color.Black;
            CaptchaControl.imageHeight = 50;
            CaptchaControl.imageWidth = 200;
            CaptchaControl.isBackgroundDynamic = false;
            CaptchaControl.isCaseSensitive = false;
            CaptchaControl.isForegroundDynamic = false;
            CaptchaControl.noiseMode = NoisyRate.MiddleNoisy;
            CaptchaControl.stringOpacity = 100;
            CaptchaControl.tooltip = "点击刷新验证码";
        }

        public CaptchaControl() : base(HtmlTextWriterTag.Img)
        {
            this.livePreview = true;
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            writer.AddStyleAttribute(HtmlTextWriterStyle.Cursor, "pointer");
            writer.AddAttribute("onclick", "this.src='CaptchaImage.aspx?id='+new Date().getTime()");
            writer.AddAttribute(HtmlTextWriterAttribute.Src, "CaptchaImage.aspx");
            writer.AddAttribute("alt", this.ToolTip);
        }

        public bool CaptchaIsExpires()
        {
            return HttpContext.Current.Session[CaptchaControl.sessionName] == null;
        }

        public bool CaptchaValidate(string userInput)
        {
            bool flag;
            DateTime now = DateTime.Now;
            DateTime item = (DateTime)HttpContext.Current.Session["Dos.Captcha.GenerateTime"];
            TimeSpan timeSpan = now - item;
            string str = (string)HttpContext.Current.Session[CaptchaControl.sessionName];
            if (str == null)
            {
                flag = false;
            }
            else if (string.IsNullOrWhiteSpace(userInput))
            {
                flag = false;
            }
            else if ((CaptchaControl.expireTime == 0 ? true : timeSpan.TotalSeconds <= (double)CaptchaControl.expireTime))
            {
                flag = (!CaptchaControl.isCaseSensitive ? str.ToUpper().Equals(userInput.Trim().ToUpper()) : str.Equals(userInput.Trim()));
            }
            else
            {
                flag = false;
            }
            return flag;
        }
    }
}